<?php

namespace app\common\model;

use app\admin\model\Admin;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 * Attachment模型
 * @controllerUrl 'routineAttachment'
 */
class Attachment extends Model
{
    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'create_time';
    protected $updateTime = null;

    protected $append = [
        'suffix',
        'full_url'
    ];

    public function getSuffixAttr($value, $row)
    {
        if ($row['name']) {
            $suffix = strtolower(pathinfo($row['name'], PATHINFO_EXTENSION));
            return $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        }
        return 'file';
    }

    public function getFullUrlAttr($value, $row)
    {
        if(strstr($row['url'], '../static/') || strstr($row['url'], '../storage/')){
            return full_url($row['url'], false);
        }else if(strstr($row['url'], '/static/') || strstr($row['url'], '/storage/')){
            return full_url('..' . $row['url'], false);
        }else{
            $cdnUrl = get_cdn_url();
            return full_url($cdnUrl . $row['url']);
        }
    }

    protected static function onBeforeInsert($model)
    {
        try {
            $repeat = $model->where([
                ['sha1', '=', $model->sha1],
                ['topic', '=', $model->topic],
                ['storage', '=', $model->storage],
            ])->find();

            if ($repeat) {
                $storageFile = path_transform(public_path() . ltrim($repeat['url'], '/'));
                if ($model->storage == 'local' && !file_exists($storageFile)) {
                    $repeat->delete();
                    return true;
                } else {
                    $repeat->quote++;
                    $repeat->last_upload_time = time();
                    $repeat->save();
                    return false;
                }
            }
            return true;
        } catch (DataNotFoundException|ModelNotFoundException|DbException $ex) {
            return false;
        }
    }

    protected static function onAfterInsert($model)
    {
        if (!$model->lastuploadtime) {
            $model->quote          = 1;
            $model->lastuploadtime = time();
            $model->save();
        }
    }

    public function admin()
    {
        return $this->belongsTo(Admin::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
